package com.ruoyi.framework.datasource.aspectj;

import com.ruoyi.common.annotation.DynamicDataSourceAnno;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.datasource.DynamicDataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;


@Aspect
@Component
@Slf4j
@Order(0)
public class DynamicDataSourceAnnoAspect {



    @Autowired
    private RedisCache redisCache;

    @Around("@annotation(com.ruoyi.common.annotation.DynamicDataSourceAnno)&& @annotation(dynamicDataSourceAnno)")
    public Object around(ProceedingJoinPoint point, DynamicDataSourceAnno dynamicDataSourceAnno) throws Throwable {


        // 获取切入的 Method
        MethodSignature joinPointObject = (MethodSignature) point.getSignature();
        Method method = joinPointObject.getMethod();


        boolean flag = method.isAnnotationPresent(DynamicDataSourceAnno.class);
        if (flag) {
            dynamicDataSourceAnno = method.getAnnotation(DynamicDataSourceAnno.class);

        } else {
            // 如果方法上没有注解，则搜索类上是否有注解
            dynamicDataSourceAnno = AnnotationUtils.findAnnotation(joinPointObject.getMethod().getDeclaringClass(), DynamicDataSourceAnno.class);
        }
        if (StringUtils.isEmpty(dynamicDataSourceAnno.value())) {
            return point.proceed();
        }
        try {
            String pageKey = Constants.DATA_SOURCE_KEY + dynamicDataSourceAnno.value();
            String source_code = redisCache.getCacheObject(pageKey);
            if (StringUtils.isNotEmpty(source_code)) {
                DynamicDataSourceContextHolder.setDataSourceType(source_code);
            }
            return point.proceed();
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            DynamicDataSourceContextHolder.clearDataSourceType();
        }
    }
}
